package org.example.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.Result;
import org.example.util.JwtUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/9/10
 * Email haijunzhou@hnit.edu.cn
 */
@Component
@Slf4j
public class MyinfoFilter extends ZuulFilter {
    @Override
    public String filterType() {

        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext cxt = RequestContext.getCurrentContext();
        HttpServletRequest request = cxt.getRequest();
        String servletPath = request.getServletPath();
        return "/blog-user/userinfo/myinfo".equals(servletPath)||
                "/user/userinfo/myinfo".equals(servletPath);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext cxt = RequestContext.getCurrentContext();
        HttpServletRequest request = cxt.getRequest();
        String jwt = request.getHeader("Authorization");
        Result result;
        if(jwt.equals("[object Object]")){
            result = new Result(-1,"未登录",null);
        } else {
            Claims user = JwtUtil.parseJWT(jwt);
            result = new Result(0,"已登录",user);
        }
        String json = null;
        try {
            json = new ObjectMapper().writeValueAsString(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        cxt.setSendZuulResponse(false);
        cxt.getResponse().setContentType("application/json;charset=utf-8");
        cxt.getResponse().addHeader("Authorization", jwt);
        cxt.setResponseBody(json);
        return null;
    }
}

